<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="view,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="[toc] 本文中用到的例子是来自于http://blog.csdn.net/lmj623565791/article/details/24300125，只是为了方便更多的人了解自定义view的过程对其中的代码进行详细的解释，如果给原作者带来的不便还请谅解，如果本文中，有什么说的不对的地方，还请指正，谢谢。对于自定义view来说我们通常走的步骤大概分为：  1、自定义View的属性2、在View">
<meta name="keywords" content="view">
<meta property="og:type" content="article">
<meta property="og:title" content="android 自定义view起步之一">
<meta property="og:url" content="http://guohaiyang.tk/post/4288d0c6.html">
<meta property="og:site_name" content="Android探索之路">
<meta property="og:description" content="[toc] 本文中用到的例子是来自于http://blog.csdn.net/lmj623565791/article/details/24300125，只是为了方便更多的人了解自定义view的过程对其中的代码进行详细的解释，如果给原作者带来的不便还请谅解，如果本文中，有什么说的不对的地方，还请指正，谢谢。对于自定义view来说我们通常走的步骤大概分为：  1、自定义View的属性2、在View">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20160419002607799">
<meta property="og:updated_time" content="2017-12-26T17:44:13.279Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="android 自定义view起步之一">
<meta name="twitter:description" content="[toc] 本文中用到的例子是来自于http://blog.csdn.net/lmj623565791/article/details/24300125，只是为了方便更多的人了解自定义view的过程对其中的代码进行详细的解释，如果给原作者带来的不便还请谅解，如果本文中，有什么说的不对的地方，还请指正，谢谢。对于自定义view来说我们通常走的步骤大概分为：  1、自定义View的属性2、在View">
<meta name="twitter:image" content="http://img.blog.csdn.net/20160419002607799">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到有关『${query}』的文章，是不是去火星了？","hits_stats":"呼哧呼哧~~ 总于找到${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://guohaiyang.tk/post/4288d0c6.html">





  <title>android 自定义view起步之一 | Android探索之路</title>
  














</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <!-- 添加github fork me -->
    <a href="https://github.com/guohaiyang1992" rel="external nofollow noopener noreferrer" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Android探索之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">吾将上下而求索</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://guohaiyang.tk/post/4288d0c6.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="guohaiyang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Android探索之路">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">android 自定义view起步之一</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-04-19T00:31:00+08:00">
                2016-04-19
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/Android/" itemprop="url" rel="index">
                    <span itemprop="name">Android</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/post/4288d0c6.html" class="leancloud_visitors" data-flag-title="android 自定义view起步之一">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读热度</span>
               
                 <span class="leancloud-visitors-count"></span> ℃
             </span>
          

          

          
            <br>
            <div class="post-wordcount">
              
                <!--
                  <span class="post-meta-divider">|</span>
                -->
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  1,973 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  9 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p> [toc]</p>
<p>本文中用到的例子是来自于<a href="http://blog.csdn.net/lmj623565791/article/details/24300125，只是为了方便更多的人了解自定义view的过程对其中的代码进行详细的解释，如果给原作者带来的不便还请谅解，如果本文中，有什么说的不对的地方，还请指正，谢谢。" rel="external nofollow noopener noreferrer" target="_blank">http://blog.csdn.net/lmj623565791/article/details/24300125，只是为了方便更多的人了解自定义view的过程对其中的代码进行详细的解释，如果给原作者带来的不便还请谅解，如果本文中，有什么说的不对的地方，还请指正，谢谢。</a><br>对于自定义view来说我们通常走的步骤大概分为：</p>
<blockquote>
<p>1、自定义View的属性<br>2、在View的构造方法中获得我们自定义的属性<br>[ 3、重写onMesure ]<br>4、重写onDraw     </p>
</blockquote>
<p>我们以上面提到的例子源码进行详细的分析：</p>
<h2 id="一、代码解析"><a href="#一、代码解析" class="headerlink" title="一、代码解析"></a><strong>一、代码解析</strong></h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line">&lt;resources&gt;</span><br><span class="line">    &lt;!-- 自定义属性 --&gt;</span><br><span class="line">    &lt;attr name=&quot;titleText&quot; format=&quot;string&quot; /&gt;</span><br><span class="line">    &lt;!-- 前面是自定义属性的名称，后面是可使用的类型,注意大小写 --&gt;</span><br><span class="line">    &lt;attr name=&quot;titleSize&quot; format=&quot;dimension&quot; /&gt;</span><br><span class="line">    &lt;!-- 这个表示只要是颜色都可以 --&gt;</span><br><span class="line">    &lt;attr name=&quot;titleColor&quot; format=&quot;color&quot; /&gt;</span><br><span class="line">    &lt;!-- 这个表示只要是资源文件即可 --&gt;</span><br><span class="line">    &lt;attr name=&quot;image&quot; format=&quot;reference&quot; /&gt;</span><br><span class="line">    &lt;!-- 这种类似于填写相对位置信息时的选项下面的枚举类型就是可选项 --&gt;</span><br><span class="line">    &lt;attr name=&quot;imageScaleType&quot;&gt;</span><br><span class="line">        &lt;enum name=&quot;fillXY&quot; value=&quot;0&quot; /&gt;</span><br><span class="line">        &lt;enum name=&quot;center&quot; value=&quot;1&quot; /&gt;</span><br><span class="line">    &lt;/attr&gt;</span><br><span class="line"></span><br><span class="line">    &lt;!-- 此处用于说明CustomImageView 有哪些属性 --&gt;</span><br><span class="line">    &lt;declare-styleable name=&quot;customImageView&quot;&gt;</span><br><span class="line">        &lt;attr name=&quot;titleText&quot; /&gt;</span><br><span class="line">        &lt;attr name=&quot;titleSize&quot; /&gt;</span><br><span class="line">        &lt;attr name=&quot;titleColor&quot; /&gt;</span><br><span class="line">        &lt;attr name=&quot;image&quot; /&gt;</span><br><span class="line">        &lt;attr name=&quot;imageScaleType&quot; /&gt;</span><br><span class="line">    &lt;/declare-styleable&gt;</span><br><span class="line"></span><br><span class="line">&lt;/resources&gt;</span><br></pre></td></tr></table></figure>
<p>这个是属性文件的内容，在 res/valuse/attr.xml  设置此属性，代码中已经做出了详细的解释，在此先不赘诉。</p>
<p>下面的是整个view的编写代码，也有了详细的注释，稍后对其中的代码片段进行解释。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line">public class customImageView extends View &#123;</span><br><span class="line">    private Bitmap mImage;</span><br><span class="line">    private int mImageScale;</span><br><span class="line">    private String mTitle;</span><br><span class="line">    private int mTextColor;</span><br><span class="line">    private int mTextSize;</span><br><span class="line">    private Rect rect;</span><br><span class="line">    private Paint mPaint;</span><br><span class="line">    private Rect mTextBound;</span><br><span class="line">    private int mWidth;</span><br><span class="line">    private int mHeight;</span><br><span class="line">    private static int IMAGE_SCALE_FITXY = 0;</span><br><span class="line"></span><br><span class="line">    public customImageView(Context context, AttributeSet attrs) &#123;</span><br><span class="line">        this(context, attrs, 0);// 此处一定要写成this</span><br><span class="line">                                // ，因为你除非设置样式否则都会执行第一或者第二个构造函数，不会经过第三个，所以第一第二个要调用第三个</span><br><span class="line">        // TODO Auto-generated constructor stub</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public customImageView(Context context) &#123;</span><br><span class="line">        this(context, null);</span><br><span class="line">        // TODO Auto-generated constructor stub</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    public customImageView(Context context, AttributeSet attrs, int defStyleAttr) &#123;</span><br><span class="line">        super(context, attrs, defStyleAttr);</span><br><span class="line">        // 获取我们自定义的属性</span><br><span class="line">        // 得到属性数组 //attrs 属性集合（哪一个对应那些值） 属性集（前面的那个的哪一个） 默认样式</span><br><span class="line">        TypedArray array = context.getTheme().obtainStyledAttributes(attrs,</span><br><span class="line">                R.styleable.customImageView, defStyleAttr, 0);// 这个地方传入的R.styleable.customImageView</span><br><span class="line">                                                                // 就是需要筛选的集合</span><br><span class="line">        int n = array.getIndexCount();</span><br><span class="line">        for (int i = 0; i &lt; n; i++) &#123;</span><br><span class="line">            int attr = array.getIndex(i); // 获取其中的一个属性</span><br><span class="line">            switch (attr) &#123;</span><br><span class="line">            case R.styleable.customImageView_image:</span><br><span class="line">                // array 通过get 方法，通过传入的标识(attr)，获取对应的属性的内容，此处的就是图片资源</span><br><span class="line">                mImage = BitmapFactory.decodeResource(getResources(),</span><br><span class="line">                        array.getResourceId(attr, 0));</span><br><span class="line">                // bitmap工厂类生成bitmap</span><br><span class="line"></span><br><span class="line">                break;</span><br><span class="line">            case R.styleable.customImageView_imageScaleType:</span><br><span class="line">                mImageScale = array.getInt(attr, 0);// 此处是整数 //放大倍数</span><br><span class="line">                break;</span><br><span class="line">            case R.styleable.customImageView_titleText:</span><br><span class="line">                mTitle = array.getString(attr);</span><br><span class="line">                break;</span><br><span class="line">            case R.styleable.customImageView_titleColor:</span><br><span class="line">                mTextColor = array.getColor(attr, 0);</span><br><span class="line">                break;</span><br><span class="line">            case R.styleable.customImageView_titleSize:</span><br><span class="line">                mTextSize = array.getDimensionPixelSize(attr, (int) TypedValue</span><br><span class="line">                        .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,</span><br><span class="line">                                getResources().getDisplayMetrics()));</span><br><span class="line">                break;</span><br><span class="line">            default:</span><br><span class="line">                break;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        array.recycle(); // 释放内存资源</span><br><span class="line">        rect = new Rect(); // 矩形画布</span><br><span class="line">        mPaint = new Paint();// 新建画笔</span><br><span class="line">        mTextBound = new Rect();// 文字的矩形画布</span><br><span class="line">        // 画笔根据文字内容测算文字矩形画布的宽高并赋值给mTextBound（此时是包裹文字的最小矩形）</span><br><span class="line">        mPaint.getTextBounds(mTitle, 0, mTitle.length(), mTextBound);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    // 测量函数</span><br><span class="line">    @Override</span><br><span class="line">    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) &#123;// 此处传入的值由父容器决定</span><br><span class="line">        // ---设置控件宽度---</span><br><span class="line">        int specMode = MeasureSpec.getMode(widthMeasureSpec); // 获取宽度的设置类型</span><br><span class="line">        int specSize = MeasureSpec.getSize(widthMeasureSpec);// 获取宽度大小</span><br><span class="line"></span><br><span class="line">        if (specMode == MeasureSpec.EXACTLY) &#123;// fill_parent,或者具体值 --type ： 精确模式</span><br><span class="line">            mWidth = specSize;</span><br><span class="line">        &#125; else &#123;//非精确模式</span><br><span class="line">            // 由图片决定的宽</span><br><span class="line">            int desireByImg = getPaddingLeft() + getPaddingRight()</span><br><span class="line">                    + mImage.getWidth();</span><br><span class="line">            // 由文字决定的宽</span><br><span class="line">            int desireByTitle = getPaddingLeft() + getPaddingRight()</span><br><span class="line">                    + mTextBound.width();</span><br><span class="line">            if (specMode == MeasureSpec.AT_MOST) &#123;// wrap_content</span><br><span class="line">                int desire = Math.max(desireByImg, desireByTitle); // 获取文字和图片之间的最大值，保证能正常显示</span><br><span class="line">                mWidth = Math.min(specSize, desire); // 此处的specSize 是父布局剩余的大小</span><br><span class="line">                                                        // 选择能正常显示和剩余大小的最小值//也就是说如果剩余值大于最小值此时图片会显示不完整，下面的代码会详细标明</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">        // ---设置高度---</span><br><span class="line">        specMode = MeasureSpec.getMode(heightMeasureSpec);</span><br><span class="line">        specSize = MeasureSpec.getSize(heightMeasureSpec);</span><br><span class="line"></span><br><span class="line">        if (specMode == MeasureSpec.EXACTLY) &#123;</span><br><span class="line">            mHeight = specSize;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            int desire = getPaddingTop() + getPaddingBottom()</span><br><span class="line">                    + mImage.getHeight() + mTextBound.height();</span><br><span class="line">            if (specMode == MeasureSpec.AT_MOST) &#123; // 同上理解</span><br><span class="line">                mHeight = Math.min(desire, specSize);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        setMeasuredDimension(mWidth, mHeight);// 设置当前控件的宽高</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void onDraw(Canvas canvas) &#123;</span><br><span class="line">        // ---------绘制一个宽度为4的矩形边框----------------</span><br><span class="line">        mPaint.setStrokeWidth(4);// 设置画笔宽度</span><br><span class="line">        mPaint.setStyle(Paint.Style.STROKE); // 设置画笔填充样式</span><br><span class="line">        mPaint.setColor(Color.CYAN);// 设置画笔颜色</span><br><span class="line">        // 绘制一个矩形，左上坐标为0,0 右下为getMeasuredWidth(), getMeasuredHeight()</span><br><span class="line">        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);</span><br><span class="line">        // --------设置这个控件的4个位置信息--------------------------------------------</span><br><span class="line">        rect.left = getPaddingLeft(); // 左上的x 坐标</span><br><span class="line">        rect.right = mWidth - getPaddingRight();// 右下的x 坐标 ，看mWidth 的组成</span><br><span class="line">                                                // 减去这个getPaddingRight等同于getPaddingLeft()+控件自身所用到的宽度</span><br><span class="line">        rect.top = getPaddingTop();// 左上的y</span><br><span class="line">        rect.bottom = mHeight - getPaddingBottom(); // 右下的y ，解释同上</span><br><span class="line"></span><br><span class="line">        // ---------开始绘制文字----------------------</span><br><span class="line">        mPaint.setColor(mTextColor);</span><br><span class="line">        mPaint.setStyle(Style.FILL);</span><br><span class="line">        // 当设置的宽度小于字体需要的宽度，将内容更改为xxx... 后面为省略号的形式</span><br><span class="line">        if (mTextBound.width() &gt; mWidth) &#123;</span><br><span class="line">            TextPaint paint = new TextPaint(mPaint);</span><br><span class="line">            String msg = TextUtils.ellipsize(mTitle,</span><br><span class="line">                    paint, // 参数含义 原始内容，画笔，真实宽度，出现“...”的方式（中间或者结尾）</span><br><span class="line">                    (float) mWidth - getPaddingLeft() - getPaddingRight(),</span><br><span class="line">                    TextUtils.TruncateAt.END).toString();</span><br><span class="line">            canvas.drawText(msg, getPaddingLeft(),</span><br><span class="line">                    mHeight - getPaddingBottom(), mPaint); // 特别指出</span><br><span class="line"></span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 正常情况，将字体居中</span><br><span class="line">            canvas.drawText(mTitle, mWidth / 2 - mTextBound.width() * 1.0f / 2,</span><br><span class="line">                    mHeight - getPaddingBottom(), mPaint);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        // 去掉使用掉的高度</span><br><span class="line">        rect.bottom -= mTextBound.height();</span><br><span class="line"></span><br><span class="line">        if (mImageScale == IMAGE_SCALE_FITXY) &#123;</span><br><span class="line">            canvas.drawBitmap(mImage, null, rect, mPaint);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            rect.left = mWidth / 2 - mImage.getWidth() / 2; // 图片大于控件宽度的时候会是负值，图片会被裁剪、、也就是说会有一部分显示不出来</span><br><span class="line">            rect.right = mWidth / 2 + mImage.getWidth() / 2;</span><br><span class="line">            rect.top = (mHeight - mTextBound.height()) / 2 - mImage.getHeight()</span><br><span class="line">                    / 2;</span><br><span class="line">            rect.bottom = (mHeight - mTextBound.height()) / 2</span><br><span class="line">                    + mImage.getHeight() / 2;</span><br><span class="line">            canvas.drawBitmap(mImage, null, rect, mPaint);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="二、疑问解答"><a href="#二、疑问解答" class="headerlink" title="二、疑问解答"></a><strong>二、疑问解答</strong></h2><p>下面对其中出现的不太容易理解的地方进行分析：</p>
<p> <strong>1. 下面这行代码的含义是什么呢？</strong>  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mTextSize = array.getDimensionPixelSize(attr, (int) TypedValue</span><br><span class="line">                    .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,</span><br><span class="line">                            getResources().getDisplayMetrics()));</span><br></pre></td></tr></table></figure>
<p>getDimensionPixelSize 这个方法的功能是获取像素值，TypedValue  .applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,<br>                                getResources().getDisplayMetrics())  这个代码的含义是将16转化为sp 格式时int 的值。也就是16sp 的int 值。</p>
<p> <strong>2. 这个将文字居中怎么理解？</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">// 正常情况，将字体居中</span><br><span class="line">        canvas.drawText(mTitle, mWidth / 2 - mTextBound.width() * 1.0f / 2,</span><br><span class="line">                mHeight - getPaddingBottom(), mPaint);</span><br></pre></td></tr></table></figure>
<p>首先我们要理解一下canvas.drawText(text, x, y, paint) 这个函数的含义：首先第一个和第四个参数的含义很容易理解，第一个是需要绘制的文本，最后一个是所使用的画笔，x,y 的话按照一般的规律来说应该是文本的位置信息，但是他的x,y 并不是一般的理解思路， 首先y 的确定上跟baseline 有关，不清楚的可以百度一下，这个就不解释了，x 和设置的文字的居中方式有关，如果设置了paint.setTextAlign(Paint.Align.CENTER)，则x 的起点默认是字符的中心位置，默认是最左侧。<br>所以上面的y 的计算其实是计算baseline ，x的位置参考下图：<br><img src="http://img.blog.csdn.net/20160419002607799" alt="x的位置理解"></p>
<h2 id="未完待续…"><a href="#未完待续…" class="headerlink" title="未完待续…"></a>未完待续…</h2>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/view/" <i="" class="fa fa-tag"> view</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/c50b688a.html" rel="next" title="对于RE文件管理器打开安卓手机的Sqlite文件速度很慢的解决办法">
                <i class="fa fa-chevron-left"></i> 对于RE文件管理器打开安卓手机的Sqlite文件速度很慢的解决办法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/276dec51.html" rel="prev" title="Android技巧总结  系列一">
                Android技巧总结  系列一 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjczNS85Mjk2"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg" alt="guohaiyang">
          <p class="site-author-name" itemprop="name">guohaiyang</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">71</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


        <!--外链播放器-->
        <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=504575633&auto=0&height=66"></iframe>

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、代码解析"><span class="nav-number">1.</span> <span class="nav-text">一、代码解析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、疑问解答"><span class="nav-number">2.</span> <span class="nav-text">二、疑问解答</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#未完待续…"><span class="nav-number">3.</span> <span class="nav-text">未完待续…</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">guohaiyang</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<!--<div class="powered-by"> -->
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  您是本站的第<span id="busuanzi_value_site_uv"></span>个访客，欢迎您的到来
</span>
<!--</div>-->

<!--屏蔽下方提示-->
<!--<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div> -->


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "db.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("h8Ih0Dm3ikBRV6HNGyvsiu8C-gzGzoHsz", "LWjl3Esuf1ArMkWbwcPbjGqV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
</html>

